package com.example.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
public class MyCallBack implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {
    /*
     * 交换机确认回调方法
     * 1.发送成功
     * 2.发送失败
     * correlationData:保存回调消息的ID及其相关信息
     * ack:交换机收到消息为true
     * cause:失败原因，成功为null
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        //失败回调
        if (ack) {
            System.out.println("消息发送成功id为" + correlationData.getId());
        } else {
            System.err.println("消息发送失败原因:" + cause + "id为" + correlationData.getId());
        }
    }

    /*
     * 当消息投递过程中不可达(只有失败才会回调)时将消息返回给生产者
     * message:消息
     * replyCode:失败码
     * exchange:交换机
     * routingKey:路由Key
     */
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        System.err.println("message:" + new String(message.getBody()));
        System.err.println("replayCode:" + replyCode);
        System.err.println("replayText:" + replyText);
        System.err.println("exchange:" + exchange);
        System.err.println("routingKey:" + routingKey);
    }

    //注入
    public MyCallBack(@Qualifier("rabbitTemplate") RabbitTemplate rabbitTemplate) {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }
}
